<template>
  <Dialog
    v-model="dialogVisible"
    width="800px"
    max-height="200px"
    title="导入"
    :before-close="() => closeDialog(formRef)"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="80px">
      <el-form-item :label="t('inventory.currency')" prop="currency">
        <el-select
          v-model="form.currency"
          :placeholder="t('inventory.currencyMsg')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="danger" link size="small" @click="handDownloadTemp"
          >（没有模板？点我下载模板）
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex flex-items-center justify-end">
        <el-button class="m-r-4" @click="closeDialog(formRef)">
          {{ t('system.parameterConfig.cancel') }}
        </el-button>
        <UploadFile
          v-if="form.currency"
          url="/admin/inventory/importPrice"
          :upload-file-button-name="t('action.importFile')"
          :file-type="['xls', 'xlsx']"
          :params="{ currency: form.currency }"
          :limit="1"
          :full-loading="true"
          :button-width="65"
          token-key="X-token"
          @upload-success-res="handleExportSuccess"
        />
        <el-button v-if="!form.currency" type="primary" @click="submit(formRef)">
          {{ t('action.importFile') }}
        </el-button>
      </div>
    </template>
  </Dialog>
  <!--  导入日志-->
  <DialogImportLogs ref="DialogImportLogsRef" />
</template>
<script setup lang="ts">
import DialogImportLogs from '../DialogImportLogs/index.vue'
import UploadFile from '@/components/UploadFile/index.vue'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules } from 'element-plus'
import { getCurrencyEnumApi, getImportTemplateApi } from '@/api/inventory'
import dayjs from 'dayjs'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)

const DialogImportLogsRef = ref<InstanceType<typeof DialogImportLogs>>()

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  currency: ''
})

const currencyList = ref<Array<Record<string, any>>>([])

const rules = ref<FormRules>({
  currency: [
    {
      required: true,
      message: t('inventory.currencyMsg'),
      trigger: 'change'
    }
  ]
})

const handDownloadTemp = async () => {
  await getImportTemplateApi(
    {
      name: 'importPrice',
      ext: 'xlsx'
    },
    `库存管理模板_${dayjs().format('YYYY.MM.DD')}.xlsx`
  )
}

const handleExportSuccess = (resp: Record<string, any>) => {
  nextTick(() => {
    DialogImportLogsRef!.value!.dialogVisible = true
    DialogImportLogsRef.value?.getBackShow(resp)
  })
  closeDialog(formRef.value)
  emit('refresh')
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    currency: ''
  }
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = async () => {
  const resp = await getCurrencyEnumApi({ field: 'all' })
  currencyList.value = resp.data.list
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped></style>
